const axios = require('axios');
const fs = require('fs');
const FormData = require('form-data');
const path = require('path');

class WechatUploader {
  constructor({ appId, appSecret }) {
    this.appId = appId;
    this.appSecret = appSecret;
    this.tokenCache = {
      value: null,
      expiresAt: 0
    };
  }

  // 获取 Access Token
  async getAccessToken() {
    const { appId, appSecret } = this;
    const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`;

    try {
      const response = await axios.get(url);
      if (response.data.access_token) {
        return response.data.access_token;
      } else {
        throw new Error('获取 Access Token 失败: ' + JSON.stringify(response.data));
      }
    } catch (error) {
      throw new Error('获取 Access Token 出错: ' + error.message);
    }
  }

  async uploadMedia(filePath) {
    const accessToken = await this.getAccessToken();
    const url = `https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=${accessToken}`;
    const form = new FormData();
    form.append('media', fs.createReadStream(filePath));

    // 根据文件类型设置正确的请求 URL
    const type = filePath.toLowerCase().endsWith('.mp3') ? 'voice' : 
      filePath.toLowerCase().endsWith('.mp4') ? 'video' : 
        'image';

    try {
      const response = await axios.post(url, form, {
        headers: {
          ...form.getHeaders(),
          'Content-Type': 'multipart/form-data'
        },
      });

      if (response.data.url) {
        const mediaUrl = response.data.url;
        console.log(`上传成功: ${filePath}, URL: ${mediaUrl}`);
        return mediaUrl;
      } else {
        console.error(`上传失败: ${filePath}, 错误信息: ${JSON.stringify(response.data)}`);
      }
    } catch (error) {
      console.error(`上传出错: ${filePath}, 错误信息: ${error.message}`);
    }
  }


  async upload(imagePath) {
    // console.log({imagePath}, 2)
    const token = await this.getAccessToken();
    // console.log({token}, 3)
    const form = new FormData();

    form.append('media', fs.createReadStream(imagePath), {
      filename: path.basename(imagePath),
      contentType: this.getMimeType(imagePath)
    });

    const { data } = await axios.post(
      `https://api.weixin.qq.com/cgi-bin/media/upload?access_token=${token}&type=image`,
      form,
      {
        headers: form.getHeaders()
      }
    );

    if (data.errcode) {
      throw new Error(`上传失败: ${data.errmsg} (${data.errcode})`);
    }

    return data.url || `https://mmbiz.qpic.cn/${data.media_id}`;
  }

  getMimeType(filePath) {
    const ext = path.extname(filePath).toLowerCase();
    const types = {
      '.png': 'image/png',
      '.jpg': 'image/jpeg',
      '.jpeg': 'image/jpeg',
      '.gif': 'image/gif',
      '.webp': 'image/webp'
    };
    return types[ext] || 'application/octet-stream';
  }
}

module.exports = { WechatUploader };
